package com.masterclient.app.businessmodule.homemodule.fragment;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import com.eoner.baselibrary.base.IBaseFragment;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.commonbean.popup.CommonPopUpBean;
import com.eoner.common.config.Config;
import com.eoner.middlelib.eventbus.event.SignRefreshEvent;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.R;
import com.masterclient.app.base.CashCommonDialog;
import com.masterclient.app.base.MessageCallBack;
import com.masterclient.app.businessmodule.homemodule.presenter.HomePresenter;
import com.masterclient.app.businessmodule.homemodule.presenter.IHomePresenter;
import com.masterclient.app.businessmodule.homemodule.view.IHomeMainView;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.HomeMessageRedEvent;
import com.eoner.middlelib.eventbus.event.HomeRefreshEvent;
import com.eoner.managerlibrary.version.VersionManager;
import com.masterclient.app.widget.ImageDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.reactivex.functions.Consumer;

public class HomePageNewFragment extends IBaseFragment {

    public static final int REQUEST_CODE = 111;
    public static String TAG = "HomePageNewFragment";
    public static HomePageNewFragment newInstance() {
        return new HomePageNewFragment();
    }

    //接口
    private IHomeMainView iHomeMainView;
    private IHomePresenter iHomePresenter;
    private boolean isVisible;

    //老通知
    private RxBus rxBus;
    //弹窗
    private CashCommonDialog ids_dialog;
    private ImageDialog imageDialog;
    boolean needVisibleShowPopup = false;
    boolean isHaveImageDialog = false;
    private List<CommonPopUpBean> homePageActivityPopupMessages;
    private int popup_index = 0;
    private Handler mHandler;
    private boolean isVisibleToUser = true;


    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_new_home, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initOnlyOnce(View rootView) {
        super.initOnlyOnce();
        //1.初始化绑定接口
        initAndBindInterface(rootView);
        //2.设置状态栏
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(mContext, iHomeMainView.mainTitleView());
        //3.获取状态栏高度
        int statusBarHeight = ImmersionBar.getStatusBarHeight(getActivity());
        //4.初始化view层
        iHomeMainView.initMainView(statusBarHeight);
        //5.获取接口
        iHomePresenter.serviceApiHomeData();
        //6.注册通知
        registerEventBus();
        //7.获取弹窗
        getDialogData();

    }


    @Override
    public void onResume() {
        MobclickAgent.onEvent(mContext, "page_index");
        super.onResume();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isVisible = !hidden;
        if (isVisible) {
            VersionManager.getInstance()
                    .setActivity(getActivity())
                    .checkVersionUpdate(false);
        }
    }

    /**
    * 初始化绑定接口
    * */
    private void initAndBindInterface(View rootView) {
        iHomeMainView = rootView.findViewById(R.id.home_main_view);
        iHomePresenter = new HomePresenter();
        iHomeMainView.bindPresenterAndInteraction(iHomePresenter);
        iHomePresenter.bindViewAndInteraction(iHomeMainView,this);
    }

    //TODO:弹窗
    public void setVisibleToUser(boolean visibleToUser) {
        isVisibleToUser = visibleToUser;
        if (homePageActivityPopupMessages != null && popup_index < homePageActivityPopupMessages.size() && isVisibleToUser && needVisibleShowPopup) {
            show_image_dialog();
        }
    }

    public void displayNotificationTipDialog() {
        if (ids_dialog == null) {
            ids_dialog = new CashCommonDialog(mContext, "系统通知未开启，活动开始后无法第一时间通知到您哦，快去开启通知吧！", "取消", "开启", 2);
        }
        ids_dialog.setOnChooseListerner(new CashCommonDialog.OnChooseListerner() {
            @Override
            public void cancel() {
                ids_dialog.dismiss();
            }

            @Override
            public void confirm() {
                ids_dialog.dismiss();
                UtilCollection.requestNotify(getActivity());
            }
        });
        ids_dialog.show();
    }

    private void getDialogData() {
        if (iHomePresenter != null) {
            iHomePresenter.serviceGetPopUpData( "index", new MessageCallBack<List<CommonPopUpBean>>() {
                @Override
                public void onSuccess(@NonNull List<CommonPopUpBean> bean) {
                    if (Config.update_app_show) {
                        return;
                    }
                    homePageActivityPopupMessages = bean;
                    if (homePageActivityPopupMessages != null) {
                        for (int i = 0; i < homePageActivityPopupMessages.size(); i++) {
                            CommonPopUpBean homePageActivityPopupMessage = homePageActivityPopupMessages.get(i);
                            boolean hasShow = homePageActivityPopupMessage.getPopup_id().equals(SPUtils.getInstance().getString(homePageActivityPopupMessage.getPopup_id() + Config.HOME_DIALOG_ID));
                            String showTime = SPUtils.getInstance().getString(homePageActivityPopupMessage.getPopup_id() + "date");
                            String currentTime = TimeUtil.get_current_time();
                            float remainDay = TimeUtil.time_remain_day(showTime, currentTime);
                            float triggerDay = Long.valueOf(homePageActivityPopupMessage.getTrigger_days());
//                        triggerDay = 0;
                            if (hasShow && remainDay < triggerDay) {
                                continue;
                            }
                            if (homePageActivityPopupMessage != null && !TextUtils.isEmpty(homePageActivityPopupMessage.getImage())) {
                                popup_index = i;
                                show_image_dialog();
                                return;
                            }
                        }
                    }
                }

                @Override
                public void onError(String s) {

                }

                @Override
                public void onFail() {

                }
            });
        }
    }

    private void show_image_dialog() {
        needVisibleShowPopup = false;
        CommonPopUpBean homePageActivityPopupMessage = null;
        if (homePageActivityPopupMessages != null && popup_index < homePageActivityPopupMessages.size()) {
            homePageActivityPopupMessage = homePageActivityPopupMessages.get(popup_index);
        }
        if (homePageActivityPopupMessage == null) {
            return;
        }
        SPUtils.getInstance().put(homePageActivityPopupMessage.getPopup_id() + Config.HOME_DIALOG_ID, homePageActivityPopupMessage.getPopup_id());
        SPUtils.getInstance().put(homePageActivityPopupMessage.getPopup_id() + "date", TimeUtil.get_current_time());
        String target = homePageActivityPopupMessage.getTarget();
        String targetId = homePageActivityPopupMessage.getTarget_id();

        if (getActivity() != null) {
            imageDialog = new ImageDialog(TextUtils.isEmpty(homePageActivityPopupMessage.getPopup_scene_id()) ? "首页弹窗" :
                    "0".equals(homePageActivityPopupMessage.getPopup_scene_id()) ? "首页新人未领券弹窗" : "1".equals(homePageActivityPopupMessage.getPopup_scene_id()) ?
                            "首页新人已领券未过期弹窗" : "首页新人领券已过期弹窗", getActivity(), homePageActivityPopupMessage.getImage(), target, targetId, "") {
                @Override
                public void dismiss() {
                    super.dismiss();
                    isHaveImageDialog = false;
                    popup_index++;
                    for (int i = popup_index; i < homePageActivityPopupMessages.size(); i++) {
                        CommonPopUpBean homePageActivityPopupMessage = homePageActivityPopupMessages.get(i);
                        boolean hasShow = homePageActivityPopupMessage.getPopup_id().equals(SPUtils.getInstance().getString(homePageActivityPopupMessage.getPopup_id() + Config.HOME_DIALOG_ID));
                        String showTime = SPUtils.getInstance().getString(homePageActivityPopupMessage.getPopup_id() + "date");
                        String currentTime = TimeUtil.get_current_time();
                        float remainDay = TimeUtil.time_remain_day(showTime, currentTime);
                        float triggerDay = Long.valueOf(homePageActivityPopupMessage.getTrigger_days());
                        if (hasShow && remainDay < triggerDay) {
                            continue;
                        }
                        if (homePageActivityPopupMessage != null && !TextUtils.isEmpty(homePageActivityPopupMessage.getImage())) {
                            popup_index = i;
                            mHandler.sendEmptyMessageDelayed(10, TextUtils.isEmpty(homePageActivityPopupMessage.getInterval_time()) ?
                                    1000 : Integer.parseInt(homePageActivityPopupMessage.getInterval_time()) * 1000);
                            return;
                        }
                    }
                }
            };
            isHaveImageDialog = true;
            imageDialog.show();
        }

    }

    //TODO:通知方法
    private void registerEventBus() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {

                    case 10:
                        if (isVisibleToUser) {
                            show_image_dialog();
                        } else {
                            needVisibleShowPopup = true;
                        }
                        break;
                }
            }
        };


        EventBusManager.register(this);
        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.SEARCH_HINT), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (iHomePresenter != null) {
                    iHomePresenter.eventBusToSearchWord(o.toString());
                }
            }
        });

        rxBus.OnEvent(rxBus.register(Config.UPDATE_DIALOG_DISMISS), new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                if ("MainActivity".equals(o.toString()) && !isHaveImageDialog && isVisible) {
                    getDialogData();
                }
            }
        });


        rxBus.OnEvent(rxBus.register(Config.MSG_UNREAD), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (Config.UNREAD > 0 || Config.TEAM_UNREAD > 0) {
                    if (Config.UNREAD >0){
                        iHomeMainView.refreshHomeDataToRedImageState(false,String.valueOf(Config.UNREAD));
                    }else if (Config.TEAM_UNREAD > 0){
                        iHomeMainView.refreshHomeDataToRedImageState(false,String.valueOf(Config.TEAM_UNREAD));
                    }
                } else {
                    iHomeMainView.refreshHomeDataToRedImageState(true,"");
                }
            }
        });

        rxBus.OnEvent(rxBus.register(Config.MSG_TEAM_UNREAD), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (Config.UNREAD > 0 || Config.TEAM_UNREAD > 0) {
                    if (Config.UNREAD >0){
                        iHomeMainView.refreshHomeDataToRedImageState(false,String.valueOf(Config.UNREAD));
                    }else if (Config.TEAM_UNREAD > 0){
                        iHomeMainView.refreshHomeDataToRedImageState(false,String.valueOf(Config.TEAM_UNREAD));
                    }
                } else {
                    iHomeMainView.refreshHomeDataToRedImageState(true,"");
                }
            }
        });

    }

    /**
    * 首页刷新 (这里MainActivity会主动调用)
    * */
    public void homeDataRefresh(HomeRefreshEvent event) {
        if (iHomePresenter != null) {
            iHomePresenter.serviceApiHomeData();
        }
        UserDataManager.getInstance().requestCustomerInfo(null);
    }

    /**
     * 签到成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void signDataRefresh(SignRefreshEvent event) {
        if (iHomePresenter != null) {
            iHomePresenter.eventBusToRefreshSignState();
        }
    }

    /**
     * 首页刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void homeMessageRedRefresh(HomeMessageRedEvent event) {
        if (iHomeMainView != null) {
            if (event.getNoticeNum() == 0) {
                iHomeMainView.refreshHomeDataToRedImageState(true,String.valueOf(event.getNoticeNum()));
            } else {
                iHomeMainView.refreshHomeDataToRedImageState(false,String.valueOf(event.getNoticeNum()));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusManager.unRegister(this);
        if (iHomePresenter != null) {
            iHomePresenter.stopAllTimerTask();
        }

        if (rxBus != null) {
            rxBus.unregister(Config.SEARCH_HINT);
            rxBus.unregister(Config.UPDATE_DIALOG_DISMISS);
            rxBus.unregister(Config.MSG_UNREAD);
            rxBus.unregister(Config.MSG_TEAM_UNREAD);
        }
    }
}
